import { useState } from 'react';
import { format, addDays, isAfter, isBefore } from 'date-fns';
import Head from 'next/head';
import { getAvailableSlots, createAppointment } from '../utils/db';

export default function Home() {
  const [selectedDate, setSelectedDate] = useState(null);
  const [availableSlots, setAvailableSlots] = useState([]);
  const [selectedSlot, setSelectedSlot] = useState(null);
  const [formData, setFormData] = useState({
    name: '',
    phone: '',
    contact_method: '',
    notes: ''
  });
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitStatus, setSubmitStatus] = useState(null);

  const handleDateChange = async (date) => {
    setSelectedDate(date);
    setSelectedSlot(null);
    
    try {
      const dateStr = format(date, 'yyyy-MM-dd');
      const bookedSlots = await getAvailableSlots(dateStr);
      
      // Generate all possible time slots (9:00-17:30, 30min intervals)
      const allSlots = [];
      let currentTime = new Date(date);
      currentTime.setHours(9, 0, 0, 0);
      
      const endTime = new Date(date);
      endTime.setHours(17, 30, 0, 0);
      
      while (isBefore(currentTime, endTime)) {
        const slotStr = format(currentTime, 'HH:mm');
        const isBooked = bookedSlots.some(slot => slot.time_slot === slotStr);
        
        allSlots.push({
          time: slotStr,
          available: !isBooked
        });
        
        currentTime = addDays(currentTime, 30 / (24 * 60));
      }
      
      setAvailableSlots(allSlots);
    } catch (error) {
      console.error('Error fetching slots:', error);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsSubmitting(true);
    
    try {
      const appointment = {
        ...formData,
        date: format(selectedDate, 'yyyy-MM-dd'),
        time_slot: selectedSlot
      };
      
      await createAppointment(appointment);
      setSubmitStatus('success');
    } catch (error) {
      console.error('Error creating appointment:', error);
      setSubmitStatus('error');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="container">
      <Head>
        <title>预约系统</title>
      </Head>

      <main>
        <h1>咨询预约系统</h1>
        
        <div className="date-picker">
          <input 
            type="date" 
            min={format(new Date(), 'yyyy-MM-dd')}
            onChange={(e) => handleDateChange(new Date(e.target.value))}
          />
        </div>
        
        {selectedDate && (
          <div className="time-slots">
            <h3>{format(selectedDate, 'yyyy年MM月dd日')} 可用时间段</h3>
            <div className="slots-grid">
              {availableSlots.map((slot) => (
                <button
                  key={slot.time}
                  className={`slot ${!slot.available ? 'booked' : ''} ${selectedSlot === slot.time ? 'selected' : ''}`}
                  disabled={!slot.available}
                  onClick={() => setSelectedSlot(slot.time)}
                >
                  {slot.time}
                </button>
              ))}
            </div>
          </div>
        )}
        
        {selectedSlot && (
          <form onSubmit={handleSubmit} className="appointment-form">
            <h3>填写预约信息</h3>
            
            <div className="form-group">
              <label>姓名 *</label>
              <input 
                type="text" 
                value={formData.name}
                onChange={(e) => setFormData({...formData, name: e.target.value})}
                required
              />
            </div>
            
            <div className="form-group">
              <label>手机号码 *</label>
              <input 
                type="tel" 
                value={formData.phone}
                onChange={(e) => setFormData({...formData, phone: e.target.value})}
                required
              />
            </div>
            
            <div className="form-group">
              <label>其他联系方式</label>
              <input 
                type="text" 
                value={formData.contact_method}
                onChange={(e) => setFormData({...formData, contact_method: e.target.value})}
                placeholder="微信/邮箱等"
              />
            </div>
            
            <div className="form-group">
              <label>备注信息</label>
              <textarea 
                value={formData.notes}
                onChange={(e) => setFormData({...formData, notes: e.target.value})}
              />
            </div>
            
            <button type="submit" disabled={isSubmitting}>
              {isSubmitting ? '提交中...' : '确认预约'}
            </button>
            
            {submitStatus === 'success' && (
              <div className="success-message">预约成功！</div>
            )}
            
            {submitStatus === 'error' && (
              <div className="error-message">预约失败，请重试</div>
            )}
          </form>
        )}
      </main>

      <style jsx>{`
        .container {
          max-width: 800px;
          margin: 0 auto;
          padding: 20px;
        }
        
        .date-picker {
          margin: 20px 0;
        }
        
        .time-slots {
          margin: 20px 0;
        }
        
        .slots-grid {
          display: grid;
          grid-template-columns: repeat(4, 1fr);
          gap: 10px;
          margin: 15px 0;
        }
        
        .slot {
          padding: 10px;
          border: 1px solid #ccc;
          background: #f0f8ff;
          cursor: pointer;
        }
        
        .slot.selected {
          background: #4CAF50;
          color: white;
        }
        
        .slot.booked {
          background: #ffdddd;
          cursor: not-allowed;
        }
        
        .appointment-form {
          margin-top: 20px;
        }
        
        .form-group {
          margin-bottom: 15px;
        }
        
        label {
          display: block;
          margin-bottom: 5px;
        }
        
        input, textarea {
          width: 100%;
          padding: 8px;
          border: 1px solid #ddd;
        }
        
        button[type="submit"] {
          background: #4CAF50;
          color: white;
          padding: 10px 15px;
          border: none;
          cursor: pointer;
        }
        
        .success-message {
          color: green;
          margin-top: 10px;
        }
        
        .error-message {
          color: red;
          margin-top: 10px;
        }
      `}</style>
    </div>
  );
}